import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
// import { loginStore } from '@/stores/login'
// import router from '@/router'

const baseURL = 'http://localhost:8080'

const instance = axios.create({
    // TODO 1. 基础地址，超时时间
    baseURL,
    timeout: 5000
})

instance.interceptors.request.use(
    (config) => {
        if (JSON.parse(localStorage.getItem('loginStore')) == null) {
            return config
        } else {
            // config.headers.Authorization = `Bearer ${token}`
            const token = JSON.parse(localStorage.getItem('loginStore')).token
            config.headers['token'] = token;
        }

        return config
    },
    (err) => Promise.reject(err)
)

instance.interceptors.response.use(
    (res) => {
        // TODO 3. 处理业务失败
        const code = res.data.code
        if (code == 0) {
            // router.push('/login')
            ElMessage({
                type: 'error',
                message: '登录失败'
            })
            return
        }

        // TODO 4. 摘取核心响应数据
        return res
    },
    (err) => {
        // TODO 5. 处理401错误
        // const userStore = useUserStore()
        // ElMessage({
        //     message: err.response.data.message || '服务异常',
        //     type: 'error'
        // })
        // console.log(err)
        // if (err.response?.status === 401) {
        //     userStore.clearUserInfo()
        //     router.push('/login')
        // }
        return Promise.reject(err)
    }
)

export default instance